package com.le.tester.tip;

import com.baidu.aip.bodyanalysis.AipBodyAnalysis;
import com.baidu.aip.face.AipFace;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.jni.Local;
import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * createTime：2022/6/15 17:34
 * description：baiDu人体计数识别
 */
@Slf4j
public class BaiDuFaceBodyTest {

    public static final String AK = "ff0p9IRvKn5pugFfct8WOtOs";

    public static final String SK = "uxDkKGLeAxztvUhWMVnPknyGkTRp3goG";

    public static final AipBodyAnalysis client = new AipBodyAnalysis("26465622", "OT2cGOTVKkIRMvxsRUNfeHFH", "wxgr3UUvnp7SsK0azPtnwLV5MzWTUhh5");

    public static final AipFace faceClient = new AipFace("31378342",
            "ff0p9IRvKn5pugFfct8WOtOs", "uxDkKGLeAxztvUhWMVnPknyGkTRp3goG");

    public void testBodyNum() throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("max_face_num", 120);
        LocalDateTime startTime = LocalDateTime.now();
        log.info("start time is {}", startTime);
        JSONObject url = faceClient.detect("https://bojuematerial-prudcut-public.oss-cn-guangzhou.aliyuncs.com/-1.jpg_2022121112230313_1670758818957.jpg",
                "URL", map);
        System.out.println(url.toString());
        LocalDateTime endTime = LocalDateTime.now();
        log.info("end time is {}", endTime);

        log.info("duration time is {}", Duration.between(startTime, endTime).toMillis());

//        //AipBodyAnalysis client = new AipBodyAnalysis("26465622", "OT2cGOTVKkIRMvxsRUNfeHFH", "wxgr3UUvnp7SsK0azPtnwLV5MzWTUhh5");
//        HashMap<String, String> param = new HashMap<>();
//        //param.put("area", null);
//        //param.put("image", "");
//        param.put("show", "false");
//
//        //String testPath = "E:\\Desktop\\2022060712044980_5556_1655284572499.jpg";
//        String testPath = "F:\\chromeDownload\\Y0002_1669035858169_未命名拍摄93285.NEF";
//        //byte[] imageByte = this.getImageBase(testPath);
////        InputStream inputStream = HttpUtil.getInputStream(testPath);
////        JSONObject response = client.bodyNum(testPath, param);
//        //byte[] imageBase = this.getImageBase(testPath);
//        //JSONObject response = client.bodyNum(imageBase, param);
//        JSONObject response = client.bodyNum(testPath, param);
//        System.out.println(response.toString());
//        Integer personNum = (Integer) response.get("person_num");
//        System.out.println("图片中的人数为：" + personNum);


    }


    /**
     * 获取token类
     */

    /**
     * 获取权限token
     *
     * @return 返回示例：
     * {
     * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
     * "expires_in": 2592000
     * }
     */
    public String getAuth() {
        // 官网获取的 API Key 更新为你注册的
        // 官网获取的 Secret Key 更新为你注册的
        return getAuth(AK, SK);
    }

    /**
     * 获取API访问token
     * 该token有一定的有效期，需要自行管理，当失效时需重新获取.
     *
     * @param ak - 百度云官网获取的 API Key
     * @param sk - 百度云官网获取的 Securet Key
     * @return assess_token 示例：
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public String getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            JSONObject jsonObject = new JSONObject(result.toString());
            System.out.println(jsonObject.getString("access_token"));
            return jsonObject.getString("access_token");
        } catch (Exception e) {
            System.err.print("获取token失败！");
            e.printStackTrace(System.err);
        }
        return null;
    }


    public byte[] getImageBase(String path) {

        InputStream input = null;
        ByteArrayOutputStream output = null;
        try {
            URL url = new URL(path);
            HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            input = httpUrl.getInputStream();

            output = new ByteArrayOutputStream();
            byte[] buf = new byte[10240];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            //output.close();
            //input.close();
            return output.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (Objects.nonNull(input)) {
                    input.close();
                }
                if (Objects.nonNull(output)) {
                    output.close();
                }
            } catch (IOException var14) {
                var14.printStackTrace();
            }
        }

    }
//    public static com.aliyun.facebody20191230.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
//        Config config = new Config()
//                // 您的 AccessKey ID
//                .setAccessKeyId(accessKeyId)
//                // 您的 AccessKey Secret
//                .setAccessKeySecret(accessKeySecret);
//        // 访问的域名
//        config.endpoint = "bojuematerial-prudcut-public.oss-cn-guangzhou.aliyuncs.com";
//        return new com.aliyun.facebody20191230.Client(config);
//    }

    public static void main(String[] args) throws Exception {

        String auth = new BaiDuFaceBodyTest().getAuth();
        System.out.println(auth);

        new BaiDuFaceBodyTest().testBodyNum();


//        //java.util.List<String> args = java.util.Arrays.asList(args_);
//        com.aliyun.facebody20191230.Client client = AliFaceBodyTest.createClient("LTAI5tDbQg5hC7tRAPDVrN6v", "NhgeBPVAY6AfbwbqyY29ybz5hfSwPw");
//        DetectBodyCountRequest detectBodyCountRequest = new DetectBodyCountRequest()
//                .setImageURL("https://bojuematerial-prudcut-public.oss-cn-guangzhou.aliyuncs.com/2022060712044980_5556_1655284572499.jpg");
//        RuntimeOptions runtime = new RuntimeOptions();
//        try {
//            // 复制代码运行请自行打印 API 的返回值
//            client.detectBodyCountWithOptions(detectBodyCountRequest, runtime);
//        } catch (TeaException error) {
//            // 如有需要，请打印 error
//            com.aliyun.teautil.Common.assertAsString(error.message);
//        } catch (Exception _error) {
//            TeaException error = new TeaException(_error.getMessage(), _error);
//            // 如有需要，请打印 error
//            com.aliyun.teautil.Common.assertAsString(error.message);
//        }


    }
}
